package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.OrderService;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class ReportServiceimpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 指定时间的营业额数据
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverReport(LocalDate startDate, LocalDate endDate) {
        List<LocalDate> list=getDateList(startDate,endDate);
        String s= StringUtils.join(list,",");
        List<Double> s2=new ArrayList<>();
        for (LocalDate date : list) {

            LocalDateTime begintime=LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endtime=LocalDateTime.of(date, LocalTime.MAX);
            Double SUM=orderMapper.summoney(begintime,endtime,5);
            if(SUM==null){
                SUM= 0.00;
            }
            s2.add(SUM);
        }
        String s3=StringUtils.join(s2,",");
        System.out.println(s3);
        return TurnoverReportVO.builder()
                .dateList(s)
                .turnoverList(s3)
                .build();
    }

    @Override
    public UserReportVO getuserreport(LocalDate startDate, LocalDate endDate) {
        List<LocalDate> list=getDateList(startDate,endDate);

        String s= StringUtils.join(list,",");
        //每天增加的人
        List<Integer> s2=new ArrayList<>();
        //一共多少人
        List<Integer> s4=new ArrayList<>();
        for (LocalDate date : list) {

            LocalDateTime begintime=LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endtime=LocalDateTime.of(date, LocalTime.MAX);
          Integer SUM= userMapper.userreport(begintime,endtime);
          Integer total=userMapper.usertotal(endtime);
          total=total==null?0:total;
          s4.add(total);
            if(SUM==null){
                SUM= 0;
            }
            s2.add(SUM);
        }
        String s3=StringUtils.join(s2,",");
        String s5=StringUtils.join(s4,",");

        return UserReportVO.builder()
                .dateList(s)
                .newUserList(s3)
                .totalUserList(s5)
                .build();
    }

    private List<LocalDate> getDateList(LocalDate startDate, LocalDate endDate) {
        List<LocalDate> list=new ArrayList<>();
        list.add(startDate);
        while (!startDate.equals(endDate)) {
            startDate = startDate.plusDays(1);
            list.add(startDate);
        }
        return list;
    }
    @Override
    public OrderReportVO getorderreport(LocalDate startDate, LocalDate endDate) {
        List<LocalDate> list=getDateList(startDate,endDate);
        String s= StringUtils.join(list,",");
        Integer totalorder=0;
        Integer completeorder=0;
        Double orderCompletionRate=0.0;
//每天增加的订单
        List<Integer> s2=new ArrayList<>();
        //一共多少订单
        List<Integer> s4=new ArrayList<>();
        for (LocalDate date : list) {

            LocalDateTime begintime=LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endtime=LocalDateTime.of(date, LocalTime.MAX);
            //每天订单数，无论成功还是取消
            Integer SUM= orderMapper.orderreport(begintime,endtime,null);
            //每天有效订单
            Integer complete=orderMapper.orderreport(begintime,endtime,5);
            complete=complete==null?0:complete;
            if(SUM==null){
                SUM= 0;
            }
            totalorder+=SUM;
            completeorder+=complete;
            s4.add(complete);
            s2.add(SUM);
        }
        orderCompletionRate=(double)completeorder/totalorder;
        String s3=StringUtils.join(s2,",");
        String s5=StringUtils.join(s4,",");
        return OrderReportVO.builder()
                .dateList(s)
                .orderCompletionRate(orderCompletionRate)
                .totalOrderCount(totalorder)
                .validOrderCountList(s5)
                .validOrderCount(completeorder)
                .orderCountList(s3)
                .build();
    }

    @Override
    public SalesTop10ReportVO gettopten(LocalDate startDate, LocalDate endDate) {
        LocalDateTime begintime=LocalDateTime.of(startDate, LocalTime.MIN);
        LocalDateTime endtime=LocalDateTime.of(endDate, LocalTime.MAX);
        List<GoodsSalesDTO> list=orderMapper.goodsaletopten(begintime,endtime);
        List<String>list1=list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
String name=StringUtils.join(list1,",");
        List<Integer>list2=list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String number=StringUtils.join(list2,",");

        return SalesTop10ReportVO.builder()
                .nameList(name)
                .numberList(number)
                .build();
    }

    @Override
    public void exxportexcel(HttpServletResponse respons) throws Exception {
        LocalDate begin=LocalDate.now().minusDays(30);
LocalDate end=LocalDate.now().minusDays(1);
        LocalDateTime start=LocalDateTime.now().minusDays(30);
        LocalDateTime down=LocalDateTime.now().minusDays(1);
        BusinessDataVO businessDataVO= workspaceService.getBusinessData(start,down);

//        FileInputStream in=new FileInputStream("template/运营数据报表模板.xlsx");
        InputStream in = getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        XSSFWorkbook workbook=new XSSFWorkbook(in);
        XSSFSheet sheet= workbook.getSheet("Sheet1");
        sheet.getRow(1).getCell(1).setCellValue("时间："+start+"至"+down);
        //第四行
        XSSFRow xssfRow=sheet.getRow(3);
        xssfRow.getCell(2).setCellValue(businessDataVO.getTurnover());
        xssfRow.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
        xssfRow.getCell(6).setCellValue(businessDataVO.getNewUsers());
        xssfRow=sheet.getRow(4);
        xssfRow.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
        xssfRow.getCell(4).setCellValue(businessDataVO.getUnitPrice());
        //明细数据
        for (int i = 0; i < 30; i++) {
            LocalDate date=begin.plusDays(i);
             businessDataVO= workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN),LocalDateTime.of(date,LocalTime.MAX));
         xssfRow=sheet.getRow(7+i);
         xssfRow.getCell(1).setCellValue(date.toString());
         xssfRow.getCell(2).setCellValue(businessDataVO.getTurnover());
         xssfRow.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
         xssfRow.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
         xssfRow.getCell(5).setCellValue(businessDataVO.getUnitPrice());
         xssfRow.getCell(6).setCellValue(businessDataVO.getNewUsers());
        }

        ServletOutputStream out=respons.getOutputStream();
        workbook.write(out);
        out.close();
        workbook.close();

    }
}
